<?php

namespace app\api\controller;


use addons\epay\library\Service;
use app\admin\model\jeek\Attestation;
use app\admin\model\jeek\Level;
use app\admin\model\jeek\shop\SkuGoods;
use app\common\controller\Api;
use app\common\model\Attachment;
use app\common\model\BrowseLog;
use app\common\model\Category;
use app\common\model\Follow;
use app\common\model\JeekMoneyLog;
use app\common\model\OrderEvaluate;
use app\common\model\Withdraw;
use tencent\api\Im;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

/**
 * 咨询师
 */
class Jeek extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize();
        $this->goodsModel = new \app\admin\model\jeek\shop\SkuGoods;
        $this->specModel = new \app\admin\model\jeek\shop\SkuSpec;
        $this->itemModel = new \app\admin\model\jeek\shop\SkuItem;
        $this->productModel = new \app\admin\model\jeek\shop\SkuProduct;
    }


    /**
     * Account:咨询师等级
     * User: Ixiangang
     * Date: 2025/2/10
     * Time: 19:22
     */
    public function levelList()
    {
        $list = Level::where('status', "normal")->order("weigh desc")->select();
        $this->success("OK", $list);
    }

    /**
     * Account:咨询师入驻
     * User: Ixiangang
     * Date: 2025/1/17
     * Time: 14:50
     */
    public function add(Request $request)
    {
        $user_id = $this->auth->id;
        $isConsultant = $this->goodsModel->where('user_id', $user_id)->find();
        if (!empty($isConsultant) && $isConsultant->examine != 3) {
            $this->error("咨询师信息已存在，不能重复认证");
        }
        $goods_id = $request->post('goods_id');
        $name = $request->post('name'); //名称
        $location = $request->post('location'); //位置
        $images = $request->post('images'); //身份证正反面 手持身份证
        if (!$images) $this->error('身份证正反面,手持身份证不能为空');
        $image = $request->post('image'); //形象照片
        if (!$image) $this->error('形象照片不能为空');
        $details = $request->post('details'); //工作经历
        $identity = $request->post('identity'); //身份证
        if (!$identity) $this->error('身份证不能为空');
        # 服务价格
        # 图文价格
        $t1 = $request->post('t1');
        $t2 = $request->post('t2');
        $t3 = $request->post('t3');
        # 音频价格
        $y1 = $request->post('y1');
        $y2 = $request->post('y2');
        $y3 = $request->post('y3');
        # 视频价格
        $s1 = $request->post('s1');
        $s2 = $request->post('s2');
        $s3 = $request->post('s3');
        if (!$t1 && !$t2 && !$t3) $this->error('请设置图文价格');
        if (!$y1 && !$y2 && !$y3) $this->error('请设置电话价格');
        if (!$y1 && !$y2 && !$y3) $this->error('请设置视频价格');
        # 教育信息
        $study = $request->post('study'); //最高学历
        $school = $request->post('school'); //毕业院校
        $major = $request->post('major'); //专业
        $enroltime = $request->post('enroltime'); //入学时间
        if (!$enroltime) $this->error('入学时间不能为空');
        $graduatetime = $request->post('graduatetime'); //毕业时间
        if (!$graduatetime) $this->error('毕业时间不能为空');
        $diploma = $request->post('diploma'); //学历证明
        # 咨询师
        $jeek_level_id = $request->post('jeek_level_id'); //咨询师等级
        if (!$jeek_level_id) $this->error('咨询师等级不能为空');
        $category_id = $request->post('category_id'); //咨询师类型
        if (!$category_id) $this->error('咨询师类型不能为空');
        $workintime = $request->post('workintime'); //从业时间
        if (!$workintime) $this->error('从业时间不能为空');
        $neighborhood = $request->post('neighborhood'); //擅长领域
        $practicing_sn = $request->post('practicing_sn'); //执业证书号
        $practicing_img = $request->post('practicing_img'); //执业证书图
        $graduate_img = $request->post('graduate_img'); //执业毕业证书
        $honor_imgs = $request->post('honor_imgs'); //荣誉证书
        $data = [
            'user_id' => $this->auth->id,
            'name' => $name,
            'identity' => $identity,
            'location' => $location,
            'images' => $images,
            'image' => $image,
            'details' => $details,
            'study' => $study,
            'school' => $school,
            'major' => $major,
            'enroltime' => strtotime($enroltime),
            'graduatetime' => strtotime($graduatetime),
            'diploma' => $diploma,
            'jeek_level_id' => $jeek_level_id,
            'category_id' => $category_id,
            'workintime' => $workintime,
            'neighborhood' => $neighborhood,
            'practicing_sn' => $practicing_sn,
            'practicing_img' => $practicing_img,
            'graduate_img' => $graduate_img,
            'honor_imgs' => $honor_imgs,
            'status' => '0',
            'examine' => '1', //待审核
            'createtime' => time(),
            'updatetime' => time()
        ];
        Db::startTrans();
        try {
            if ($goods_id) {
                Db::table('fa_jeek_shop_sku_goods')->where('id', $goods_id)->update($data);
                $goodsId = $goods_id;
            } else {
                $goodsId = $this->goodsModel->insertGetId($data);
            }

            # 添加服务规格
            $groups = ["类型", "时长"];
            $items = [["图文咨询", "电话咨询", "视频咨询"], ["15分钟", "60分钟", "240分钟"]];
            $skus = [
                ['attr' => ["图文咨询", "15分钟"], 'price' => $t1],
                ['attr' => ["图文咨询", "60分钟"], 'price' => $t2],
                ['attr' => ["图文咨询", "240分钟"], 'price' => $t3],
                ['attr' => ["电话咨询", "15分钟"], 'price' => $y1],
                ['attr' => ["电话咨询", "60分钟"], 'price' => $y2],
                ['attr' => ["电话咨询", "240分钟"], 'price' => $y3],
                ['attr' => ["视频咨询", "15分钟"], 'price' => $s1],
                ['attr' => ["视频咨询", "60分钟"], 'price' => $s2],
                ['attr' => ["视频咨询", "240分钟"], 'price' => $s3],
            ];
            //写入 spec
            $spec = [];
            foreach ($groups as $k => $v) {
                if (!count($items[$k])) {
                    continue;
                }
                $spec[] = ['name' => $v, 'goods_id' => $goodsId];
            }
            $res = $this->specModel->saveAll($spec);
            // 写入item
            $item = [];
            foreach ($res as $k => $v) {
                foreach ($items[$k] as $kk => $vv) {
                    $item[] = [
                        'name' => $vv,
                        'spec_id' => $v['id'],
                        'goods_id' => $goodsId // 仅为了方便删除
                    ];
                }
            }
            $res = $this->itemModel->saveAll($item);
            // 写入规格商品
            $product = [];
            foreach ($skus as $k => $v) {
                $v['key'] = $this->getKey($res, $v['attr']);
                $v['goods_id'] = $goodsId;
                unset($v['attr']);
                $product[] = $v;
            }
            $this->productModel->saveAll($product);
            if (!$goods_id) $this->goodsModel->where('id', $goodsId)->update(['weigh' => $goodsId]);




            Db::commit();
        } catch (Exception $e) {
            throw new Exception('添加出错'); //让外部回滚
        }
        $this->success("入驻成功", ['goods_id' => $goodsId]);
    }

    /**
     * Account:服务类型数据整合
     * User: Ixiangang
     * Date: 2025/1/18
     * Time: 10:46
     */
    public function getKey($ids, $attr)
    {
        $key = '';
        foreach ($attr as $v) {
            foreach ($ids as $k => $vv) {
                if ($vv->name === $v) {
                    $key .= '_' . $vv->id;
                }
            }
        }
        return ltrim($key, '_');
    }


    /**
     * Account:重新认证咨询师
     * User: Ixiangang
     * Date: 2025/1/18
     * Time: 10:45
     */
    public function recertification()
    {
        $user_id = $this->auth->id;
        $goods_id = $this->goodsModel->where('user_id', $user_id)->value('id');
        if (!$goods_id) {
            $this->error("咨询师信息不存在");
        }
        $this->specModel->where('goods_id', 'in', $goods_id)->delete();
        $this->itemModel->where('goods_id', 'in', $goods_id)->delete();
        $this->productModel->where('goods_id', 'in', $goods_id)->delete();
        $this->success("OK", ['goods_id' => $goods_id]);
    }

    /**
     * Account:咨询师信息
     * User: Ixiangang
     * Date: 2025/1/18
     * Time: 09:40
     */
    public function person()
    {
        $info = $this->goodsModel->where('user_id', $this->auth->id)->find();
        if (empty($info)) $this->error('未认证咨询师');
        $info->images = explode(",", $info->images);
        # 查询咨询师等级
        $info->jeek_level_name = Level::where('id', $info->jeek_level_id)->value('name');
        # 查询类别
        $info->category_name = Category::where('id', 'in', $info->category_id)->column('name');
        # 咨询师认证费
        $siteCertificationFee = config('site.certification_fee');
        $info->certification_fee = bcsub($siteCertificationFee, $info->payfees, 2);
        # 判断咨询师 是否需要补交 保证金
        if ($info->payfees == $siteCertificationFee){
            $info->supplementary_payment = 1; //不需要补交
        }else{
            $info->supplementary_payment = 0; //需要补交
        }
        # 查询用户手机号
        $info->mobile = \app\common\model\User::where('id', $this->auth->id)->value('mobile');
        # 查询评价数
        $info->orderEvaluateCount = OrderEvaluate::where('goods_id', $info->id)->count();
        $this->success('OK', $info);
    }


    /**
     * Account:咨询师上下班
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 16:23
     */
    public function saveStatus()
    {
        $status = $this->request->get('status');  //1=上班，0=下班
        if ($status != 1 && $status != 0) $this->error("参数错误");
        $goods = $this->goodsModel->where('user_id', $this->auth->id)->find();
        if (empty($goods)) $this->error("咨询信息错误");
        $goods->status = $status;
        $goods->work = $status;
        $goods->updatetime = time();
        $goods->save();
        $this->success("OK");
    }


    /**
     * Account:编辑咨询信息
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 16:44
     */
    public function profileGoods()
    {
        $goods = $this->goodsModel->where('user_id', $this->auth->id)->find();
        $name = $this->request->post('name'); //名称
        $gender = $this->request->post('gender', 1); //性别:0=男，1=女
        $image = $this->request->post('image'); //头像
        $video = $this->request->post('video'); //个人视频
        $profileitem = [];
        if ($name) {
            $exists = $this->goodsModel->where('name', $name)->where('id', '<>', $goods->id)->find();
            if ($exists) {
                $this->error(__('咨询师名称重复'));
            }
            $goods->name = $name;
            $itemarr['Tag'] = "Tag_Profile_IM_Nick";
            $itemarr['Value'] = $name;
            $profileitem[] = $itemarr;
        }
        if ($image) {
            $goods->image = $image;
            $itemarr['Tag'] = "Tag_Profile_IM_Image";
            $itemarr['Value'] = cdnurl($image,true);
            $profileitem[] = $itemarr;
        }
        if ($video) {
            $goods->video = $video;
        }
        $goods->gender = $gender;
        $goods->updatetime = time();
        $goods->save();
        $im = new Im();
        $im->set_info($goods->tencent_account, $profileitem);
        $this->success();
    }

    /**
     * Account:我的钱包
     * User: Ixiangang
     * Date: 2025/2/14
     * Time: 09:10
     */
    public function money()
    {
        $goods = $this->goodsModel->where('user_id', $this->auth->id)->field('id,money')->find();
        if (empty($goods)) $this->success("咨询师信息不存在");
        $list = JeekMoneyLog::where(['goods_id' => $goods->id])->order('id desc')->field("id,money,before,after,memo,createtime")->select();
        $goods->moneylist = !empty($list) ? $list : [];
        $this->success('OK', $goods);
    }



    /**
     * Account:咨询师提现
     * User: Ixiangang
     * Date: 2025/2/14
     * Time: 09:19
     */
    public function jeekWithdraw()
    {
        $user = $this->auth->getUser();
        if (!$user->wechat_account || !$user->wechat_name) {
            $this->error("请先绑定微信账号");
        }
        $goods = $this->goodsModel->where('user_id', $this->auth->id)->field('id,money')->find();
        if (empty($goods)) $this->success("咨询师信息不存在");

        $price = $this->request->post('price'); //提现金额

        if (!is_numeric($price)) {
            $this->error("请输入数字");
        }
        if ($price <= 0) {
            $this->error("提现金额必须大于0");
        }
        if ($price > $goods->money) {
            $this->error('可提现资金不足！');
        }
        $info = Withdraw::where(['goods_id' => $goods->id, 'status' => 1, 'position' => '2'])->find();
        if (!empty($info)) {
            $this->error(__('你有一笔提现订单再审核，请勿重复提交'));
        }
        $data = [
            'goods_id' => $goods->id,
            'price' => $price,
            'position' => 2, //咨询师
            'type' => 1, //微信
            'status' => 1, //待审核
            'wechat_account' => $user->wechat_account,
            'wechat_name' => $user->wechat_name,
            'reason_rejection' => '',
            'createtime' => time(),
        ];
        $rs = Withdraw::create($data);
        if ($rs) {
            $memo = "提现";
            $this->goodsModel->money(-$price, $goods->id, $memo);
            $this->success("申请提现成功");
        }
        $this->error("参数错误");
    }


    /**
     * 咨询师认证缴费
     * User: Ixiangang
     * Date: 2025/1/18
     * Time: 10:07
     */
    public function provePay()
    {
        $user_id = $this->auth->id;
        $pay_type = $this->request->post('pay_type');
        if (!in_array($pay_type, ['wechat', 'alipay'])) {
            $this->error('传参不正确');
        }
        if ($pay_type == "wechat") {
            if (!$this->auth->app_openid) $this->error('请先绑定微信');
        }
        # 查询咨询师 是否审核通过
        $goods = $this->goodsModel->where('user_id', $user_id)->find();
        if (empty($goods)) {
            $this->error("咨询师信息不存在");
        }
        if ($goods->examine == 1) {
            $this->error('待审核，审核通过后缴纳咨询师认证费');
        }
        if ($goods->examine == 3) {
            $this->error('审核拒绝，重新认证后缴纳咨询师认证费');
        }
        $data = [
            'order_sn' => 'R_' . date('YmdHis') . rand(1111, 9999),
            'user_id' => $user_id,
            'goods_id' => $goods->id,
            'pay_price' => bcsub(config('site.certification_fee'), $goods->payfees, 2),
            'pay_type' => $pay_type,
        ];
        $row = Attestation::create($data);
        if ($row) {
            $params = [
                'amount' => $data['pay_price'],
                'orderid' => $data['order_sn'],
                'type' => $pay_type,
                'title' => "咨询师认证费/补缴",
                'notifyurl' => $this->request->root(true) . '/api/pay/notify/paytype/' . $pay_type,
                'method' => 'app',
                'openid' => $this->auth->app_openid,
            ];
            $pay = Service::submitOrder($params);
            $this->success('支付成功', compact('pay', 'pay_type'));
        }
        $this->error("支付错误");
    }


    /**
     * Account:推荐咨询师
     * User: Ixiangang
     * Date: 2025/1/18
     * Time: 14:41
     */
    public function index()
    {
        $keyword = $this->request->post('keyword'); //模糊查询
        $category_id = $this->request->post('category_id');
        $list = $this->goodsModel->getListPage(['keyword' => $keyword, 'category_id' => $category_id]);
        $this->success("OK", $list);

    }

    /**
     * Account:咨询师详情
     * User: Ixiangang
     * Date: 2025/1/21
     * Time: 08:46
     */
    public function info(Request $request)
    {
        $user_id = $this->auth->id;
        $goods_id = $request->post('goods_id');
        $info = $this->goodsModel->getInfo($goods_id, $user_id);
        # 记录浏览记录
        (new BrowseLog())->addBrowse($user_id, $goods_id, 1);
        $this->success("OK", $info);
    }


    /**
     * Account:关注咨询师 取消关注
     * User: Ixiangang
     * Date: 2025/2/7
     * Time: 15:33
     */
    public function follow()
    {
        $user_id = $this->auth->id;
        $goods_id = $this->request->post('goods_id');
        $type = $this->request->post('type'); //1=关注，0=取消关注
        $goods = $this->goodsModel->where('id', $goods_id)->find();
        if (empty($goods)) $this->error("咨询师不存在");
        if (!in_array($type, ['1', '0'])) {
            $this->error("参数错误");
        }
        if ($type == 1) {
            Follow::create([
                'user_id' => $user_id,
                'goods_id' => $goods_id,
                'createtime' => time(),
            ]);
            SkuGoods::where('id',$goods->id)->setInc('likes');
            $this->success("关注成功");
        } else {
            Follow::where('goods_id', $goods_id)->where('user_id', $user_id)->delete();
            $this->success("取消关注");
        }
        $this->error("错误信息");
    }


    /**
     * Account:我的关注列表
     * User: Ixiangang
     * Date: 2025/2/8
     * Time: 13:52
     */
    public function followlist(Request $request)
    {
        $user_id = $this->auth->id;
        $goods_ids = Follow::where('user_id', $user_id)->column('goods_id');
        if (empty($goods_ids)) {
            $this->success("OK", []);
        }
        $list = $this->goodsModel->getListPage(['goods_ids' => $goods_ids]);
        $this->success("OK", $list);
    }

    /**
     * Account:浏览记录
     * User: Ixiangang
     * Date: 2025/2/11
     * Time: 19:08
     */
    public function browseList()
    {
        $user_id = $this->auth->id;
        $goods_ids = BrowseLog::where(['user_id' => $user_id, 'type' => '1'])->column('goods_id');
        if (empty($goods_ids)) {
            $this->success("OK", []);
        }
        $list = $this->goodsModel->getListPage(['goods_ids' => $goods_ids]);
        $this->success("OK", $list);
    }


    /**
     * Account:评价记录
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 14:51
     */
    public function orderEvaluateList()
    {
        $goods_id = $this->request->post('goods_id');
        if (empty($goods_id)) {
            $this->error("参数错误");
        }
        $list = (new OrderEvaluate())->getListPage(['goods_id' => $goods_id]);
        $this->success("OK", $list);
    }


}